﻿using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using Keep.API.Common.L.Dtos;
using MediatR;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.Ocsp;

namespace Keep.API.Appliction.Command.DepartmentFile
{
    /// <summary>
    /// 部门列表命令处理器
    /// </summary>
    public class DepartmentListHandler : IRequestHandler<DepartmentListCommon, ResultPage<DepartmentListDto>>
    {
        private readonly IBaseRepositorys<Department> _DepartmentRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRep"></param>
        public DepartmentListHandler(IBaseRepositorys<Department> baseRep)
        {
            _DepartmentRep = baseRep;
        }

       
        /// <summary>
        /// 迭代实现树形表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<DepartmentListDto>> Handle(DepartmentListCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<DepartmentListDto>() { Code = (int)CodeEnum.success, Messege = "获取成功" };
            try
            {
                // 一次性查询所有部门数据到内存中
                var allDepartments = _DepartmentRep.GetAll().ToList();

                // 先根据OrgName筛选（如果有要求）
                var filteredDepartments = string.IsNullOrEmpty(request.OrgName)? allDepartments: allDepartments.Where(c => c.OrgName == request.OrgName).ToList();

                // 创建一个字典来存储部门ID和对应的DepartmentListDto
                var departmentDtos = new Dictionary<int, DepartmentListDto>();
                foreach (var department in filteredDepartments)
                {
                    var deparDto = new DepartmentListDto
                    {
                        OrgId = department.OrgId,
                        OrgName = department.OrgName,
                        OrgCode = department.OrgCode,
                        ParentId = department.ParentId,
                        ParentName = department.ParentId > 0 ? allDepartments.FirstOrDefault(c => c.OrgId == department.ParentId)?.OrgName : "",
                        CreateName = department.CreateName,
                        CreateDate = department.CreateDate,
                        UpdateName = department.UpdateName,
                        UpdateDate = department.UpdateDate,
                        Children = new List<DepartmentListDto>()
                    };
                    departmentDtos[department.OrgId] = deparDto;
                }

                // 构建树形结构
                var topLevelDepartments = new List<DepartmentListDto>();
                foreach (var department in filteredDepartments)
                {
                    if (department.ParentId == 0)
                    {
                        topLevelDepartments.Add(departmentDtos[department.OrgId]);
                    }
                    else if (departmentDtos.ContainsKey(department.ParentId))
                    {
                        departmentDtos[department.ParentId].Children.Add(departmentDtos[department.OrgId]);
                    }
                }

                // 分页处理
                result.totalCount = topLevelDepartments.Count; // 总记录数
                result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.pageSize); // 总页数
                var pagedDepartments = topLevelDepartments.OrderBy(c => c.OrgId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = pagedDepartments;
            }
            catch (Exception ex)
            {
                result.Code = (int)CodeEnum.error;
                result.Messege = ex.Message;
            }
            return result;
        }
    }
}
#region 老版本代码
//    public async Task<ResultPage<DepartmentListDto>> Handle(DepartmentListCommon request, CancellationToken cancellationToken)
//    {
//        var result = new ResultPage<DepartmentListDto>() { Code = (int)CodeEnum.success, Messege = "获取成功" };
//        try
//        {
//            // 一次性查询所有部门数据到内存中
//            var allDepartments = _DepartmentRep.GetAll().ToList();

//            // 先根据OrgName筛选（如果有要求）
//            var filteredDepartments = string.IsNullOrEmpty(request.OrgName)
//              ? allDepartments
//                : allDepartments.Where(c => c.OrgName == request.OrgName).ToList();

//            // 获取顶级部门（ParentId为0的部门）
//            var topLevelDepartments = filteredDepartments.Where(c => c.ParentId == 0).ToList();

//            List<DepartmentListDto> deparDtos = new List<DepartmentListDto>();
//            foreach (var item in topLevelDepartments)
//            {
//                DepartmentListDto deparDto = MapToDepartmentListDto(item, allDepartments);
//                deparDtos.Add(deparDto);
//            }

//            result.totalCount = deparDtos.Count();//总记录数
//            result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.pageSize);//总页数
//            deparDtos = deparDtos.OrderBy(c => c.OrgId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
//            result.Data = deparDtos;
//        }
//        catch (Exception ex)
//        {
//            result.Code = (int)CodeEnum.error;
//            result.Messege = ex.Message;
//        }
//        return result;
//    }
//    private DepartmentListDto MapToDepartmentListDto(Department department, List<Department> allDepartments)
//    {
//        DepartmentListDto deparDto = new DepartmentListDto();
//        deparDto.OrgId = department.OrgId;
//        deparDto.OrgName = department.OrgName;
//        deparDto.OrgCode = department.OrgCode;
//        deparDto.ParentId = department.ParentId;
//        if (department.ParentId > 0)
//        {
//            var parentDepartment = allDepartments.FirstOrDefault(c => c.OrgId == department.ParentId);
//            deparDto.ParentName = parentDepartment?.OrgName;
//        }
//        else
//        {
//            deparDto.ParentName = "";
//        }
//        deparDto.CreateName = department.CreateName;
//        deparDto.CreateDate = department.CreateDate;
//        deparDto.UpdateName = department.UpdateName;
//        deparDto.UpdateDate = department.UpdateDate;

//        // 查找并设置子部门
//        deparDto.Children = allDepartments.Where(c => c.ParentId == department.OrgId).Select(child => MapToDepartmentListDto(child, allDepartments)).ToList(); 
//        return deparDto;
//    }
//}
///// <summary>
// /// 部门列表命令处理器
// /// </summary>
// public class DepartmentListHandler:IRequestHandler<DepartmentListCommon,ResultPage<DepartmentListDto>>
// {
//         private readonly IBaseRepositorys<Department> _DepartmentRep;
//     /// <summary>
//     /// 构造函数
//     /// </summary>
//     /// <param name="baseRep"></param>
//         public DepartmentListHandler(IBaseRepositorys<Department> baseRep)
//         {
//              _DepartmentRep = baseRep;
//         }

//     public async Task<ResultPage<DepartmentListDto>> Handle(DepartmentListCommon request, CancellationToken cancellationToken)
//     {
//         var result = new ResultPage<DepartmentListDto>() { Code = (int)CodeEnum.success, Messege = "获取成功" };
//         try
//         {
//             // 一次性查询所有部门数据到内存中
//             var allDepartments = _DepartmentRep.GetAll().ToList();

//             // 先根据OrgName筛选（如果有要求）
//             var filteredDepartments = string.IsNullOrEmpty(request.OrgName)
//               ? allDepartments
//                 : allDepartments.Where(c => c.OrgName == request.OrgName).ToList();

//             // 获取顶级部门（ParentId为0的部门）
//             var topLevelDepartments = filteredDepartments.Where(c => c.ParentId == 0).ToList();

//             List<DepartmentListDto> deparDtos = new List<DepartmentListDto>();
//             foreach (var item in topLevelDepartments)
//             {
//                 DepartmentListDto deparDto = MapToDepartmentListDto(item, allDepartments);
//                 deparDtos.Add(deparDto);
//             }

//             result.totalCount = deparDtos.Count();//总记录数
//             result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.pageSize);//总页数
//             deparDtos = deparDtos.OrderBy(c => c.OrgId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
//             result.Data = deparDtos;
//         }
//         catch (Exception ex)
//         {
//             result.Code = (int)CodeEnum.error;
//             result.Messege = ex.Message;
//         }
//         return result;
//     }
//     private DepartmentListDto MapToDepartmentListDto(Department department, List<Department> allDepartments)
//     {
//         DepartmentListDto deparDto = new DepartmentListDto();
//         deparDto.OrgId = department.OrgId;
//         deparDto.OrgName = department.OrgName;
//         deparDto.OrgCode = department.OrgCode;
//         deparDto.ParentId = department.ParentId;
//         if (department.ParentId > 0)
//         {
//             var parentDepartment = allDepartments.FirstOrDefault(c => c.OrgId == department.ParentId);
//             deparDto.ParentName = parentDepartment?.OrgName;
//         }
//         else
//         {
//             deparDto.ParentName = "";
//         }
//         deparDto.CreateName = department.CreateName;
//         deparDto.CreateDate = department.CreateDate;
//         deparDto.UpdateName = department.UpdateName;
//         deparDto.UpdateDate = department.UpdateDate;

//         // 查找并设置子部门
//         deparDto.Children = allDepartments.Where(c => c.ParentId == department.OrgId).Select(child => MapToDepartmentListDto(child, allDepartments)).ToList(); 
//         return deparDto;
//     }
// } 

#endregion